<template>
  <div class="render-form-item" :style="itemStyle">
    <!-- 栅格控件 -->
		<template v-if="widget.type == 'grid'">
			<render-grid
				:key="widget.key"
				:rules="rules"
				:widget="widget"
				:controls="controls"
				:values="values"
				:validateInfo="validateInfo"
				v-on="$listeners"
			/>
		</template>

    <!-- 收缩板 -->
    <template v-if="widget.type === 'collapse'">
      <render-collapse
				:key="widget.key"
				:widget="widget"
        :rules="rules"
			/>
    </template>

    <!-- 表格 -->
		<template v-else-if="widget.type === 'table'">
			<render-table
				:key="widget.key"
				:widget="widget"
        :rules="rules"
			/>
		</template>

    <!-- 分割线 -->
		<template v-else-if="widget.type === 'halvingLine'">
			<render-line :key="widget.key" :widget="widget" />
		</template>

    <!-- 布局控件 -->
		<template v-else-if="widget.type=='easyLayout'">
      <render-layout
				:widget="widget"
				:controls="controls"
				:rules="rules"
				:validateInfo="validateInfo"
				v-on="$listeners"
			/>
    </template>

    <template v-else>
      <sg-form-item
        :class="{
          'sg-form-item-required': isRequired,
          'hidden-label': parentType === 'table' || needHideLabel.includes(widget.type) || !widget.options.title
        }"
        :item-for="widget.key"
        :label="widget.options.title"
        :prop="primaryKey"
        :label-width="labelWidth"
        :required="isRequired"
        :rules="rules[primaryKey]"
      >
        <sg-tooltip
					placement="bottom-start"
					:content="tips"
					:disabled="!tips"
					:tabindex="-1"
        >
          <!--静态文本控件-->
          <template v-if="widget.type == 'label'" >
            <sf-static-text
              :content="widget.options.content"
              :defaultPrintValue="widget.options.defaultPrintValue"
              width="100%"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit : 'auto'"
            />
          </template>
          <!--文本框-->
          <template v-if="widget.type == 'input'" >
            <sf-input
              v-model="dataModel"
              :defaultPrompt="defaultPrompt"
              :height="widget.options.multipleLines ? 'auto' : '36px'"
              :multipleLines="widget.options.multipleLines || false"
              :readOnlyBorder="widget.options.readOnlyBorder"
              :commonWordType="widget.options.commonWordType"
            />
          </template>
          <!--标题控件-->
          <template v-if="widget.type == 'title'" >
            <div>
              <sf-title
                :title='widget.options.title'
                width='100%'
                :height="widget.options.height ? widget.options.height + widget.options.heightUnit : '35px'"
                :styleType="widget.options.styleType"
                :fontSize="'14px'"
                :paddingTop="widget.options.paddingTop"
                :paddingBottom="widget.options.paddingBottom"
                :paddingLeft="widget.options.paddingLeft"
                :paddingRight="widget.options.paddingRight"
              />
            </div>
          </template>
          <!--隐藏控件-->
          <template v-if="widget.type == 'hidden'">
            <sf-hidden
              v-model="dataModel"
              :width="widget.options.width ? widget.options.width + widget.options.widthUnit : '100%'"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit :'36px'"
            />
          </template>
          <!--数值控件-->
          <template v-if="widget.type == 'number'" >
            <sf-number
              v-model="dataModel"
              :numType="widget.options.numType"
              :toFixed="widget.options.toFixed"
              :handleZero="widget.options.handleZero"
              :defaultPrompt="defaultPrompt"
              width="100%"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit : '36px'"
              :readOnlyBorder="widget.options.readOnlyBorder"
              :inputStyle="widget.options.inputStyle"
            />
          </template>
          <!--自动编号控件-->
          <template v-if="widget.type == 'autoNumber'" >
            <sf-autoNumber
              v-model="dataModel"
              :key="primaryKey"
              :isAutoNumber="widget.options.isAutoNumber"
              :rid="widget.options.numberingFormula"
              :jid="jid"
              :readOnlyBorder="widget.options.readOnlyBorder"
              width="100%"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit : '36px'"
              :defaultPrompt="defaultPrompt"
            ></sf-autoNumber>
          </template>
          <!--图片控件-->
          <template v-if="widget.type == 'imagebox'">
            <sf-image-box
              :width="widget.options.width ? widget.options.width + widget.options.widthUnit : '100%'"
              v-model="dataModel"
              :maxNumber="widget.options.maxNumber"
              class="item-image-box"
              :imageWidth="widget.options.imageWidth ? widget.options.imageWidth + widget.options.imageWidthUnit : '100px'"
              :imageHeight="widget.options.imageHeight ? widget.options.imageHeight + widget.options.imageHeightUnit : '100px'"
            />
          </template>
          <!--二维码控件-->
          <template v-if="widget.type == 'qrcode'">
            <sf-qrcode
              :class="{'widget-border-error': isRequired && !dataModel }"
              :content="dataModel ? dataModel : widget.options.defaultValue"
              :qrcodeType="widget.options.qrcodeType"
              :width="widget.options.width ? widget.options.width + widget.options.widthUnit : '200px'"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit : '200px'"
            />
          </template>
          <!--组织项控件-->
          <template v-if="widget.type == 'organization'">
            <sf-organization
              :key="primaryKey"
              :readOnlyBorder="widget.options.readOnlyBorder"
              :organizationType="widget.options.organizationType"
              :readOnly="widget.options.permission.indexOf('readonly') > -1"
              width="100%"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit : ''"
              :inputMode="widget.options.inputMode"
              v-model="dataModel"
              :multiple="widget.options.multiple"
              :filtersExpression='widget.options.evaluateExpression'
              :props="{ label:'text', value: 'id' }"
              :disableType="widget.options.disableType"
              :defaultPrompt="defaultPrompt"
            />
          </template>
          <!-- 签名意见 -->
          <template v-if="widget.type == 'approvalOpinion'">
            <sf-signOption
              v-model="dataModel"
              :defaultPrompt="defaultPrompt"
              width="100%"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit:widget.options.multipleLines?'auto':'36px'"
              :multipleLines="widget.options.multipleLines"
              :readOnlyBorder="widget.options.readOnlyBorder"
              :commonWordType="widget.options.commonWordType"
            />
          </template>
          <!-- 签名人 -->
          <template v-if="widget.type == 'approvalSignature'">
            <sf-sign-chat
              v-model="dataModel"
              width="100%"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit : '36px'"
              :readOnlyBorder="widget.options.readOnlyBorder"
            />
          </template>
          <!--签名日期-->
          <template v-if="widget.type == 'approvalDate'">
            <sf-sign-time
              v-model="dataModel"
              :readOnlyBorder="widget.options.readOnlyBorder"
              :dateFormat="widget.options.dateFormat"
              width="100%"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit : ''"
							:defaultPrompt="defaultPrompt"
            />
          </template>
          <!--签名印章-->
          <template v-if="widget.type == 'approvalStmap'">
            <sf-sign-statmp
              :class="{'widget-border-error': isRequired && !dataModel }"
              v-model="dataModel"
              :key="primaryKey"
              :readOnlyBorder="widget.options.readOnlyBorder"
              width="100%"
              :jid="business.jid"
              :linkDefinitionKey="business.linkDefinitionKey"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit : ''"
              :placeholder="widget.options.defaultPrompt"
							:btnText="widget.options.btnText"
							:showType="widget.options.showType"
            />
          </template>
          <!--按钮控件 -->
          <template v-if="widget.type == 'button'" >
            <sf-button
              :dropDownButton="widget.options.dropDownButton"
              :icon="widget.options.icon"
              :readOnlyBorder="widget.options.readOnlyBorder"
              :title="widget.options.title"
              width="100%"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit : ''"
              :expression="widget.options.evaluateExpression"
              :type="widget.options.type"
              :outline="widget.options.outline || false"
            >
              {{widget.options.title}}
            </sf-button>
          </template>
          <!--单选框控件-->
          <template v-if="widget.type == 'radiobox'">
            <sf-radio
              v-model="dataModel"
              :options="widget.options.options"
              width="100%"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit : ''"
              :layout="widget.options.layout"
              :hiddenName="widget.options.hiddenName"
              class="item-radio-box"
            />
          </template>
          <!--复选框控件-->
          <template v-if="widget.type == 'checkbox'">
            <sf-checkbox
              v-model="dataModel"
              :key="primaryKey"
              :options="widget.options.options"
              width="100%"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit : ''"
              :layout="widget.options.layout"
              :hiddenName="widget.options.hiddenName"
              class="item-checkbox-box"
            />
          </template>
          <!--日期控件-->
          <template v-if="widget.type=='datebox'">
            <sf-date-box
              v-model="dataModel"
              :dateFormat="widget.options.dateFormat"
              :readOnlyBorder="widget.options.readOnlyBorder"
              width="100%"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit : ''"
              :timestamp="widget.options.timestamp"
              :defaultPrompt="defaultPrompt"
            />
          </template>
          <!--选择器控件-->
          <template v-if="widget.type == 'multiSelection'">
            <sf-select
              ref="sfSelect"
              class="formdesignerGenFormItem"
              filterable
              v-model="dataModel"
              :multiple="widget.options.multiple"
              :optionList="widget.options.options"
              :inputMode="widget.options.inputMode"
              :readOnlyBorder="widget.options.readOnlyBorder"
              :linkfield="widget.options.linkfield"
              :linkexp="widget.options.linkexp"
              :filter="!widget.options.isHideSearch"
              :saveValue="saveValueForSelect"
              width="100%"
              :height="widget.options.height ? widget.options.height : 'auto'"
              :onlySelectSon="widget.options.onlySelectSon"
              :defaultPrompt="defaultPrompt"
            />
          </template>
          <!--图标控件-->
          <template v-if="widget.type.toLowerCase() == 'icon'">
            <div :style="[
              {height: widget.options.fontSize ? widget.options.fontSize + 'px' : ''},
              {lineHeight: widget.options.fontSize ? widget.options.fontSize + 'px' : ''}
            ]">
              <sf-icon
                width="100%"
                :iconType="widget.options.icon"
                :fontSize="widget.options.fontSize"
              />
            </div>
          </template>
          <!-- 级联选择器控件 -->
          <template v-if="widget.type == 'combobox'">
            <sf-cascader
              v-model="dataModel"
              :key="primaryKey"
              :options="widget.options.options"
              :readOnlyBorder="widget.options.readOnlyBorder"
              width="100%"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit : ''"
              :prop="propCascader"
              :filterable="true"
              :defaultPrompt="defaultPrompt"
            />
          </template>
          <!-- 富文本编辑器控件 -->
          <template v-if="widget.type == 'richbox'">
            <sf-editor
              class="sf_editor_test"
              v-model="dataModel"
              width="100%"
              :height="widget.options.height ? widget.options.height + widget.options.heightUnit : '100%'"
              :commonWordType="widget.options.commonWordType"
              :bcode="business.bcode"
            />
          </template>
          <!-- 占位符 -->
          <template v-if="widget.type == 'placeholder'">
            <div
              :style="{
                height: widget.options.height ? widget.options.height + widget.options.heightUnit:'50px',
                width: widget.options.width ? widget.options.width + widget.options.widthUnit:'100%'
              }"
            />
          </template>
          <!--轮播控件-->
          <template v-if="widget.type=='swiper'">
            <sf-swiper
              :cHeight="widget.options.imgheight"
              :cWidth="widget.options.imgwidth"
              :autoplay="widget.options.autoplay"
              :interval="widget.options.interval"
              :arrow="widget.options.arrow"
              :loop="widget.options.loop"
              :slides="widget.options.slides"
            />
          </template>
          <!-- 坐标提取和地图定位 -->
          <template v-if="widget.type == 'areaMap' || widget.type == 'lineMap' || widget.type == 'pointMap'">
            <sf-map
              v-model="dataModel"
              :width="widget.options.width + widget.options.widthUnit"
              :height="widget.options.height + widget.options.heightUnit"
              :hideInputCoors="widget.options.hideInputCoors"
              :showInputCoorsBtn="widget.options.showInputCoorsBtn"
              :showMapDrawBtn="widget.options.showMapDrawBtn"
              :showPositionBtn="widget.options.showPositionBtn"
              :fractionLength="widget.options.fractionLength"
              :coordinateType="widget.options.coordinateType"
              :mapType="widget.options.mapType"
              :openMapType="widget.options.openMapType"
              :showPointZAxis="widget.options.showPointZAxis"
              :customImportData="widget.options.mapCustomImportData"
              :spatialRef="widget.options.spatialRef"
              :customBtns="widget.options.mapCustomBtns"
              :dataFormat="widget.options.dataFormat"
              :permission="getPermission"
            />
          </template>
          <!-- 图表控件 -->
          <template v-if="widget.type == 'chart'">
            <sf-chart
              v-model="dataModel"
              :title="widget.options.title"
              :showTitle="widget.options.showTitle"
              :titleXPosition="widget.options.titleXPosition"
              :type="widget.options.chartType"
              :name="widget.options.name"
              :color="widget.options.color"
              :width="widget.options.width"
              :widthUnit="widget.options.widthUnit"
              :height="widget.options.height"
              :heightUnit="widget.options.heightUnit"
              :boAliasName="widget.options.boAliasName"
              :boParams="widget.options.boParams"
              :xField="widget.options.xField"
              :yField="widget.options.yField"
              :showLabel="widget.options.showLabel"
              :labelPosition="widget.options.labelPosition"
              :axisLabelRotate="widget.options.axisLabelRotate"
              :barWidth="widget.options.barWidth"
              :barCategoryGap="widget.options.barCategoryGap"
              :barStack="widget.options.barStack"
              :legendOption="widget.options.legendOption"
              :stackArea="widget.options.stackArea"
              :lineSmooth="widget.options.lineSmooth"
              :expression="widget.options.chartExpression"
              :outRadius="widget.options.outRadius"
              :inRadius="widget.options.inRadius"
              :permission="getPermission"
            />
          </template>
          <!-- 自定义控件 -->
          <template v-if="widget.type == 'custom'">
            <div ref="HtmlAndJsStr" v-html="customCode" />
          </template>
        </sg-tooltip>
        <div class="clear"></div>
      </sg-form-item>
    </template>
  </div>
</template>

<script>
import RenderGrid from '../RenderGrid.vue'
import RenderCollapse from '../RenderCollapse.vue'
import RenderTable from '../RenderTable.vue'
import RenderLine from '../RenderLine.vue'
import RenderLayout from '../RenderLayout'

export default {
  name: 'RenderFormItem',

  components: {
    RenderGrid, RenderCollapse, RenderTable, RenderLine, RenderLayout
  },

  props: {
    widget: {
      type: Object,
      default: () => {
        return {}
      }
    },
    rules: {
      type: [Object, Array],
      default: () => {
        return {}
      }
    },
    controls: {
      type: Object,
      default: () => {
        return {}
      }
    },
    values: {
      type: Object
    },
    rowEditData: {
      type: Object,
      default: () => null
    },
    // 父级控件类型
    parentType: {
      type: String,
      default: ''
    },
    // 表单验证提示信息
    validateInfo: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },

  data () {
    return {
      needHideLabel: [
        'grid',
        'table',
        'tab',
        'collapse',
        'tree',
        'button',
        'halvingLine',
        'nav',
        'childFroms',
        'label',
        'approvalCounter',
        'Icon',
        'icon',
        'qrcode',
        'title',
        'chart',
        'easyLayout',
        'attachment',
        'processDisplay',
        'step',
        'stepLine',
        'linkForm'
      ],
      customCode: '',
      propCascader: {
        label: 'label',
        value: 'value',
        children: 'children'
      },
      businessProcess: {
        bcode: '',
        jid: '',
        linkDefinitionKey: ''
      }
    }
  },

  computed: {
    dataModel: {
      get () {
        let currentValue
        const { type, key } = this.widget
        
        let value = null
        if (this.rowEditData) {
          value = this.rowEditData.value == null ? '' : this.rowEditData.value
        } else {
          value = this.$store.state.form.formValue[key]
        }
        if (type === 'datebox' || type === 'approvalDate') {
          currentValue = value ? value === '#now'
            ? new Date() : typeof value === 'number'
              ? timestampToTime(value) : value : null;
        } else {
          //多选为数组
          if (
            this.widget.options.multiple && typeof value == 'string' ||
            type === 'checkbox' ||
            type === 'combobox'
          ) {
            if (value !== null && typeof value == 'object') currentValue = value;
            currentValue = value ? value.trim() ? value.split(',') : [] : [];
          } else {
            currentValue = value
          }
        }
        return currentValue
      },
      set (value) {
        if (value === this.dataModel) {
          return
        }
        const { type, options, key } = this.widget
        if (
          type === 'checkbox'
					|| options.multiple && (type === 'multiSelection' || type === 'organization')
					|| type === 'combobox'
        ) {
          // 需要拼接为字符串，子表保存的接口(saveSubFormData)格式为application/json，
          // 但要求必须传递字符串，否则会报错
          value = value ? value.join(',') : '';
        }
        this.setFormFieldValue(key, value)
        this.$forceUpdate()
      }
    },
    itemStyle () {
      const options = this. widget.options
      const type = this.widget.type
      const style = {
        width: options.width
          ? options.width + options.widthUnit
          : this.labelLayout ? '' : '100%',
        height: type === 'sfMap' && options.mapHeight && options.mapHeightUnit === '%'
          ? options.mapHeight + 'vh'
          : 'auto'
      }
      // 标签页控件内部会计算宽度
      if (type === 'tab') {
        style.width = '100%'
      }

      if (type === 'collapse') {
        style.width = 'auto'
        const marginData = ['marginTop', 'marginBottom', 'marginLeft', 'marginRight']
        marginData.forEach(key => {
          const value = options[key]
          if (value) {
            const hasUnit = value && /(px|%)/.test(value)
            style[key] = hasUnit ? value : value + 'px'
          }
        })
      }

      return style
    },
    primaryKey () {
      return this.widget.key.replace('.','_')
    },
    labelWidth () {
      return Number(this.widget.options.labelWidth)
    },
    isRequired () {
      const rules = this.rules[this.primaryKey]
      return rules ? rules.some((value) => value.required == true) : false
    },
    tips () {
      return this.validateInfo[this.primaryKey] ? this.validateInfo[key].toolTipStatus : ''
    },
    defaultPrompt () {
      const { defaultPrompt = '' } = this.widget.options

      const promptMap = new Map([
        [['organization', 'multiSelection', 'combobox', 'datebox', 'approvalDate'], '请选择'], // 组织项 下拉选择器 级联控件 日期控件 签名日期
        [['autoNumber'], '自动编号'], // 编号控件
        [['input', 'number', 'approvalOpinion'], defaultPrompt] // 文本框 数值控件 签名意见
      ])

      let result = ''
      const action = [...promptMap]
      action.forEach(([key, value]) => {
        key.includes(this.widget.type) && (result = value)
      })

      return result
    },
    getPermission() {
      let permission = this.rowEditData && this.rowEditData.parentPermission ? this.rowEditData.parentPermission : this.widget.options.permission;
      if(this.isViewMode && !permission.includes('hidden') && !permission.includes('always')) {
        return ['readonly']
      }else{
        return permission;
      }
    }
  },

  methods: {
    setFormFieldValue(key, value) {
      this.$listeners.setFormValue && this.$listeners.setFormValue({ key, value })
      this.$store.dispatch('form/updateValue', { key, value })
    }
  }
}
</script>

<style lang="scss" scoped>
.render-form-item {
  /deep/ .hidden-label {
    > label.sg-form-item-label {
      display: none !important;
      width: 0 !important;
    }

    > .sg-form-item-content {
      margin-left: 0 !important;
      //TODO: 处理静态文本框控件有滚动条问题
      .ql-editor {
        padding: 0 15px;
        line-height: 36px;
      }

      > .sg-tooltip {
        width: 100%;
        display: block;

        .sg-tooltip-rel {
          display: block;
        }
      }
    }
  }

  .sg-form-item-required::after{
    content: '*';
    display: inline-block;
    line-height: 1;
    font-family: SimSun;
    color: #ff4064;
    position: absolute;
    left: -15px;
    top: 50%;
    transform: translate(0,-50%);
  }
}
</style>
